package cn.bincker.mycaptcha.basic.impl;

import cn.bincker.mycaptcha.CacheManager;
import cn.bincker.mycaptcha.CaptchaFactory;
import cn.bincker.mycaptcha.CaptchaService;
import cn.bincker.mycaptcha.basic.AnswerStorage;
import cn.bincker.mycaptcha.basic.entity.MyAnswer;
import cn.bincker.mycaptcha.basic.entity.MyCaptcha;

import javax.servlet.http.HttpServletRequest;

public class DefaultCaptchaServiceImpl<C extends MyCaptcha, A extends MyAnswer> implements CaptchaService<C> {
    private final CaptchaFactory<C, A> captchaFactory;
    private final CacheManager<C, A> cacheManager;
    private final AnswerStorage<A> answerStorage;

    public DefaultCaptchaServiceImpl(CaptchaFactory<C, A> captchaFactory, CacheManager<C, A> cacheManager, AnswerStorage<A> answerStorage) {
        this.captchaFactory = captchaFactory;
        this.cacheManager = cacheManager;
        this.answerStorage = answerStorage;
    }

    @Override
    public C getCaptcha(HttpServletRequest request) {
        var question = cacheManager.shooting().orElseGet(captchaFactory::build);
        answerStorage.store(request, question.getAnswer());
        return question.getCaptcha();
    }
}
